<template>
  <div class="chat-view">
    <div class="tabs">
      <div
        :class="['tab', { active: activeTab === 'agent' }]"
        @click="activeTab = 'agent'"
      >
        Agent
      </div>
      <div
        :class="['tab', { active: activeTab === 'calculator' }]"
        @click="activeTab = 'calculator'"
      >
        计算器
      </div>
    </div>

    <!-- Agent Tab Content -->
    <div class="chat-messages" v-show="activeTab === 'agent'">
      <div class="chat-messages" ref="chatContainer">
        <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message', msg.role]"
        >
          <div class="messageItem" v-if="msg.role === 'assistant'">
            <div class="assistant-avatar">A</div>
            <div class="message-text">
              <MessageContent :message="msg.content" />
            </div>
          </div>
          <div class="messageItem" style="justify-content: flex-end" v-else>
            <div class="message-text">{{ msg.content }}</div>
            <div class="user-avatar">U</div>
          </div>
        </div>
      </div>

      <div class="chat-input-area">
        <form @submit.prevent="sendMessage">
          <div class="input-group">
            <input
              v-model="userInput"
              type="text"
              placeholder="请输入您的问题..."
              :disabled="loading"
            />
            <button type="submit" :disabled="!userInput.trim() || loading">
              {{ loading ? '发送中...' : '发送' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Calculator Tab Content -->
    <div v-show="activeTab === 'calculator'" class="calculator-tab">
      <MRPCalculator />
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref, triggerRef } from 'vue' // 导入triggerRef方法
import { type StreamEvent } from '@/services/mrpService' // 引入流式输出相关类型
import MessageContent from '@/components/MessageContent.vue'
import MRPCalculator from '@/components/MRPCalculator.vue'

const API_BASE_URL = '/api'

// 添加 tab 控制
const activeTab = ref<'agent' | 'calculator'>('agent')

interface Message {
  role: 'user' | 'assistant';
  content: string;
}

const messages = ref<Message[]>([
  { role: 'assistant', content: '您好！我是您的 MRP计划Agent，请告诉我您的问题。' }
])

const userInput = ref('')
const loading = ref(false)
const chatContainer = ref<HTMLElement | null>(null)

onMounted(() => {
  scrollToBottom()
})

const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}

const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return

  // 添加用户消息
  const userMsg: Message = { role: 'user', content: userInput.value }
  messages.value.push(userMsg)
  const userText = userInput.value
  userInput.value = ''
  loading.value = true
  scrollToBottom()

  try {
    // 创建一个助手消息占位
    const assistantMsg: Message = {
      role: 'assistant',
      content: ''
    }
    messages.value.push(assistantMsg)

    // 构建查询参数
    const params = { query: userText }
    const queryParams = new URLSearchParams()
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined) {
        queryParams.append(key, value.toString())
      }
    })

    // 构建EventSource URL
    const eventSourceUrl = `${API_BASE_URL}/calculate_mrp_stream?${queryParams.toString()}`


    // 统一的消息处理函数
    const handleMessageEvent = (event: MessageEvent, assistantMsg: Message, eventSource: EventSource) => {

      // 解析SSE数据格式 (data: {...}\n\n)
      const dataString = event.data

      if (!dataString) return

      // 处理SSE格式，数据可能以"data: "开头
      let jsonDataString = dataString
      if (dataString.startsWith('data: ')) {
        jsonDataString = dataString.substring(6) // 移除 "data: " 前缀
      } else if (dataString.startsWith('data:')) {
        jsonDataString = dataString.substring(5) // 移除 "data:" 前缀
      }

      // 如果数据以换行符结尾，移除它
      if (jsonDataString.endsWith('\n')) {
        jsonDataString = jsonDataString.slice(0, -1)
      }

      try {
        const streamEvent: StreamEvent = JSON.parse(jsonDataString)


        if (streamEvent.type === 'chunk') {
          console.log(streamEvent.content)
          // 实时更新消息内容，实现打字机效果
          assistantMsg.content += streamEvent.content

          // 强制触发Vue的响应式更新
          triggerRef(messages)
          scrollToBottom()
        } else if (streamEvent.type === 'end') {
          // 流结束，关闭连接

          eventSource.close()
          clearInterval(checkConnection)
          loading.value = false
        } else if (streamEvent.type === 'error') {
          // 处理错误
          console.error('Stream error:', streamEvent.content)
          // 只有当还没有内容时才替换全部内容，否则追加错误信息
          if (assistantMsg.content) {
            // assistantMsg.content += '\n\n错误信息: ' + streamEvent.content
          } else {
            assistantMsg.content = '抱歉，处理过程中出现错误：' + streamEvent.content
          }
          eventSource.close()
          clearInterval(checkConnection)
          loading.value = false
        } else if (streamEvent.type === 'result') {
          // 忽略result类型消息，因为我们只关注文本流
          // result包含最终的结构化数据，可以用于其他用途

        }
      } catch (e) {
        console.error('解析流数据失败:', e)

        // 如果不是JSON格式，直接将数据添加到内容中
        assistantMsg.content += jsonDataString
        scrollToBottom()
      }
    }

    // 使用流式API实现实时输出效果
    const eventSource = new EventSource(eventSourceUrl, { withCredentials: true })


    // 监听所有事件类型
    eventSource.addEventListener('open', (event) => {

    })

    // 添加对不同类型事件的监听
    eventSource.addEventListener('message', (event) => {

      handleMessageEvent(event, assistantMsg, eventSource)
    })

    eventSource.onerror = (error) => {
      console.error('流式传输错误 (via onerror):', error)

      assistantMsg.content = '网络错误，请稍后重试。'
      eventSource.close()
      loading.value = false
    }

    // 定期检查连接状态的函数
    const checkConnection = setInterval(() => {

      if (eventSource.readyState === EventSource.CLOSED) {

        clearInterval(checkConnection)
      }
    }, 100)
  } catch (error) {
    console.error('对话失败:', error)
    messages.value.push({
      role: 'assistant',
      content: '网络错误，请稍后重试。'
    })
    loading.value = false
  }
}
</script>

<style scoped>
.chat-view {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  max-width: none;
  margin: 0;
  padding: 20px;
  box-sizing: border-box;
  background-color: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 20px;
}

.tab {
  padding: 12px 24px;
  cursor: pointer;
  border-bottom: 3px solid transparent;
  transition: all 0.3s ease;
}

.tab.active {
  border-bottom: 3px solid #10a37f;
  color: #10a37f;
  font-weight: 500;
}

.tab:hover {
  background-color: #f8f9fa;
}

.calculator-tab {
  flex: 1;
  overflow-y: auto;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
  padding: 10px;
}

.message {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  width: 100%;
}


.messageItem{
  display: flex;
  width: 100%;
}
.user-avatar {
  border-radius: 50%;
  width: 32px;
  flex-shrink: 0;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #5436da;
  color: white;
}

.assistant-avatar {
  border-radius: 50%;
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #10a37f;
  color: white;
}

.message-text {
  max-width: 85%;

  margin:0 15px;
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
  background-color: #f1f3f4;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  color: #202123;
  align-self: center;
}

.message.user .message-text {
  background-color: #ffffff;
  border: 1px solid #e5e5e5;
}

.chat-input-area {
  margin-top: 16px;
}

.input-group {
  display: flex;
  gap: 10px;
}

.input-group input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #dadce0;
  border-radius: 24px;
  font-size: 16px;
  outline: none;
  background-color: #ffffff;
  color: #202123;
}

.input-group input:focus {
  border-color: #10a37f;
}

.input-group input:disabled {
  background-color: #f1f3f4;
  color: #5f6368;
}

.input-group button {
  padding: 12px 24px;
  background-color: #10a37f;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  font-size: 16px;
}

.input-group button:hover {
  background-color: #0d8a6a;
}

.input-group button:disabled {
  background-color: #dadce0;
  cursor: not-allowed;
}
</style>
